package com.hllxd.hism.star.config.mvc;

import com.hllxd.hism.star.util.ConsoleContext;
import com.hllxd.hism.star.util.CounterLogger;
import com.hllxd.hism.star.util.ThreadLocalManager;
import com.hllxd.hism.star.util.TraceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiyong.lxy
 * @date 2022.04.20
 */

@Component public class AtomicInterceptor extends HandlerInterceptorAdapter {
    private static final Logger log = LoggerFactory.getLogger(AtomicInterceptor.class);
//    private static PvLoggerManager pvLogger = null;

    public static boolean setConsoleContext(HttpServletRequest request) {
        try {
            ConsoleContext context = new ConsoleContext();
            context.setRequest(request);
            context.setBeginMs(System.currentTimeMillis());
            String traceId = request.getHeader("traceID");
            if (traceId == null) {
                context.setTraceId(TraceUtil.newTraceId());
            } else {
                context.setTraceId(traceId);
            }
            String username = "developer";
            log.info("username: {}", username);
            context.setUserID(username);

            log.info("set context success. traceId: {}", traceId);
            ThreadLocalManager.setConsoleContext(context);
        } catch (Exception e) {
            log.warn("error in preHandle getUser. url is:" + request.getRequestURL(), e);
            return false;
        }
        return true;
    }

    @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // log.info("request header: {}", JSON.toJSONString(request.getHeaderNames()));
        if (!setConsoleContext(request)) {
            log.warn("set local content failed.");
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {
        CounterLogger.write(response, request.getRequestURI());
        ThreadLocalManager.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}
